#!/bin/bash

# 设置环境变量
export UESTUDIO="/d/vc/UEStudio"
export UESTUDIO_SRC="$UESTUDIO/src"
export wxWIN="/d/vc/wxWidgets-3.2.7"
export wxINCLUDE="$wxWIN/include"
export wxSETUP_H="$wxWIN/lib/wx/include/msw-unicode-3.2"
export wxLIB_DLL="$wxWIN/lib"

# 添加更多wxWidgets头文件路径
export CXXFLAGS="-I. -I$UESTUDIO_SRC/include -I$UESTUDIO_SRC/sdk/wxscintilla/include -I$wxINCLUDE -I$wxSETUP_H -I$wxINCLUDE/msvc -D__WXMSW__ -DcbDEBUG -DWXUSINGDLL -std=c++17 -DWX_PRECOMP"
export LDFLAGS="-L$wxLIB_DLL -L$UESTUDIO_SRC/devel"

echo "🚀 AICoder 插件编译开始 (修复版)..."
echo "=========================================="

# 清理旧文件
echo "清理旧编译文件..."
find . -name "*.o" -delete
rm -f AICoder.dll

# 编译函数
compile_file() {
    local file=$1
    echo "编译: $file"
    if g++ $CXXFLAGS -c "$file" -o "${file%.cpp}.o" 2>&1 | grep -v "warning:"; then
        echo "✅ $file 编译成功"
        return 0
    else
        echo "❌ $file 编译失败"
        return 1
    fi
}

# 逐个编译文件，便于调试
echo "步骤1: 编译协作框架..."
compile_file "CollaborativeCore/CollaborationProtocol.cpp" || exit 1
compile_file "CollaborativeCore/RealTimeEditor.cpp" || exit 1
compile_file "ModelModuleSystem/ModelComponent.cpp" || exit 1
compile_file "ModelModuleSystem/ComponentAssembler.cpp" || exit 1
compile_file "GlobalRegistry/ComponentRegistry.cpp" || exit 1

echo "步骤2: 编译主插件..."
compile_file "AICoder.cpp" || exit 1

echo "步骤3: 链接生成DLL..."
echo "链接对象文件..."
if g++ -shared -o AICoder.dll \
    CollaborativeCore/*.o \
    ModelModuleSystem/*.o \
    GlobalRegistry/*.o \
    AICoder.o \
    $LDFLAGS \
    -lcodeblocks -lwx_mswu_core-3.2 -lwx_baseu-3.2 -lwxscintilla 2>&1; then
    
    echo "✅ AICoder.dll 链接成功！"
    echo "文件信息:"
    ls -lh AICoder.dll
    
    # 检查依赖
    echo "检查DLL依赖..."
    ldd AICoder.dll 2>/dev/null || echo "无法检查依赖"
    
    # 尝试部署
    echo "步骤4: 部署插件..."
    if [ -d "$UESTUDIO/output/plugins" ]; then
        cp AICoder.dll "$UESTUDIO/output/plugins/" && echo "✅ 插件已部署到 $UESTUDIO/output/plugins/"
    else
        echo "⚠️  插件目录不存在，创建目录..."
        mkdir -p "$UESTUDIO/output/plugins"
        cp AICoder.dll "$UESTUDIO/output/plugins/" && echo "✅ 插件已部署到 $UESTUDIO/output/plugins/"
    fi
    
else
    echo "❌ 链接失败，尝试简化链接..."
    if g++ -shared -o AICoder.dll *.o $LDFLAGS -lcodeblocks; then
        echo "✅ AICoder.dll 简化链接成功！"
        ls -lh AICoder.dll
    else
        echo "❌ 所有链接尝试都失败了"
        exit 1
    fi
fi

echo "=========================================="
echo "🎉 AICoder 插件编译完成！"
